<?php

/**
 * 实现发布内容的Tag
 */
class Tags extends BaseModel {
    
    public $table = "tags";
    
    /**
     * 设置项目标签
     * @param integer $itemid
     * @param array $tags
     * @param string $type
     */
    public function set_tag($itemid, $blogid, $tags, $type = "post") {
        $tags = array();
        foreach($_POST['post_tags'] as $v) {
            $v = str_ireplace(array(
                '\'', '"'
            ), "", trim(strip_tags($v)));
            if($v) {
                $tags[] = $v;
            }
        }
        if(!$tags or !is_array($tags)) {
            return false;
        }
        $tag_ids = $this->get_tag_ids_by_tags($tags);
        $tag_items_table = $this->get_table("tag_items");
        $sql = "SELECT * FROM {$tag_items_table} 
                WHERE type = :type AND itemid = :itemid AND blogid = :blogid
                AND tagid IN (0, '%s')";
        $sql = sprintf($sql, implode("','", $tag_ids));
        $stmt = $this->db->prepare($sql);
        $stmt->execute(array(
            ":type" => $type,
            ":itemid" => $itemid,
            ":blogid" => $blogid
        ));
        
        $exists = $stmt->fetchAll();
        if($exists) {
            $exists_ids = array();
            foreach($exists as $e) {
                $exists_ids = $e["tagid"];
            }
            //计算所有tag和已经存在tag的差集
            $tag_ids = array_diff($tag_ids, $exists_ids);
        }
        
        if(!$tag_ids) {
            return false;
        }
        
        /**
         * 写入tag_items
         */
        $sql = "INSERT INTO {$tag_items_table}(tagid, itemid, blogid, type)VALUES(:tagid, :itemid, :blogid, :type)";
        $stmt = $this->db->prepare($sql);
        foreach($tag_ids as $ti) {
            $stmt->execute(array(
                ":tagid" => $ti,
                ":itemid"=> $itemid,
                ":blogid"=> $blogid,
                ":type"  => $type
            ));
        }
    }
    
    /**
     * 检测已经存在的tag 并且将差集插入到数据库
     * @return array $tagids 返回所有的tag id
     */
    private function get_tag_ids_by_tags($tags) {
        $the_tags = implode("','", $tags);
        $sql = "SELECT id, name FROM {$this->table} WHERE name IN (0, '{$the_tags}')";
        $q = $this->db->query($sql);
        $tagids = array();
        $the_tags = array();
        if($q) {
            $data = $q->fetchAll();
            foreach($data as $row) {
                $tagids[] = $row["id"];
                $the_tags[] = $row["name"];
            }
        }
        
        //获得所有tag和已存在tag的差集
        $new_tags = array_diff($tags, $the_tags);
        if($new_tags) {
            foreach($new_tags as $nt) {
                $rs = $this->insert(array(
                    "name" => $nt
                ));
                if($rs) {
                    $tagids[] = $rs;
                }
            }
        }
        
        return $tagids;
    }
    
}
